#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/3 17:35
# @File    : tk_tab2.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn


from tkinter import *
import tkinter.ttk as ttk
import tkinter as tk
from PIL import Image, ImageTk

# https://blog.csdn.net/weixin_45558166/article/details/122079072
class MyTable(ttk.Frame):

    def __init__(self, master):
        self.master = master
        super().__init__(master)
        self.pack()  # frame加入root
        tableColumns = ['序号', '权限', '用户', '密码']
        tableValues = [
            ["1", "0", "user1", "password1"],
            ["2", "1", "user2", "password2"],
            ["3", "1", "user3", "password3"],
            ["4", "2", "user4", "password4"],
            ["5", "2", "user5", "password5"],
            ["6", "3", "user4", "password6"],
            ["7", "2", "user7", "password7"],
            ["8", "2", "user8", "password8"],
            ["9", "1", "user9", "password9"]
        ]
        # 设置滚动条
        self.xscroll = Scrollbar(self, orient=HORIZONTAL, command=self.on_X_ScrollCommand)
        self.yscroll = Scrollbar(self, orient=VERTICAL, command=self.on_Y_ScrollCommand)
        self.xscroll.pack(side=BOTTOM, fill=X)
        self.yscroll.pack(side=RIGHT, fill=Y)
        self.table = ttk.Treeview(
            master=self,  # 父容器
            columns=tableColumns,  # 列标识符列表
            height=30,  # 表格显示的行数
            show='tree headings',  # 隐藏首列
            style='Treeview',  # 样式
            xscrollcommand=self.xscroll.set,  # x轴滚动条
            yscrollcommand=self.yscroll.set  # y轴滚动条
        )
        # self.xscroll.config(command=self.table.xview)
        # self.yscroll.config(command=self.table.yview)
        self.table.pack()  # TreeView加入frame

        self.table.heading(column="#0", text="用户头像", anchor=CENTER,
                           command=lambda: print("您点击了“用户头像”列"))  # 设置#0列表头
        for i in range(len(tableColumns)):
            self.table.heading(column=tableColumns[i], text=tableColumns[i], anchor=CENTER,
                               command=lambda: print(tableColumns[i]))  # 设置除#0列以外的表头
            self.table.column(tableColumns[i], minwidth=100, anchor=CENTER, stretch=True)  # 设置列
        style = ttk.Style(master)
        # 数据字体大小
        style.configure("Treeview", rowheight=50, font=("Arial", 10, 'bold'))
        # 设置标题字体
        style.configure("Treeview.Heading", font=("Arial", 8, 'bold'))

        self.image = ImageTk.PhotoImage(Image.open("img.png"))
        for i, data in enumerate(tableValues):
            print(data)
            self.table.insert('', 'end', text="☑️这里是头像◻️︎", image=self.image, value=data, tags=str(i))

        self.entry = tk.Entry(self, highlightthickness=1, bg='#F3F3F4', textvariable='')
        self.entry.bind("<FocusIn>", self.on_FocusIn)
        self.entry.bind("<FocusOut>", self.on_FocusOut)
        self.table.bind("<Double-1>", self.on_Double_1)
        self.table.bind("<MouseWheel>", self.on_MouseWheel)
        self.entry.bind("<Return>", self.on_Return)

    # 焦点在输入条时触发
    def on_FocusIn(self, event):
        print("输入内容")
        pass

    # 焦点离开输入条时触发
    def on_FocusOut(self, event):
        text = self.entry.get()  # 获取输入条内容
        self.table.set(self.row, self.column, text)  # 表格数据设置为输入条内容
        self.entry.place_forget()  # 隐藏输入条
        # self.xscroll.pack(side=BOTTOM, fill=X)
        # self.yscroll.pack(side=RIGHT, fill=Y)
        print("输入结束")

    # 鼠标左键双击触发
    def on_Double_1(self, event):
        if str(event.widget) == ".!mytable.!treeview":  # 双击触发的是否为表格
            table = event.widget
            for item in table.selection():  # 取消表格选取
                table.selection_remove(item)

            self.row = table.identify_row(event.y)  # 点击的行
            self.column = table.identify_column(event.x)  # 点击的列
            col = int(str(table.identify_column(event.x)).replace('#', ''))  # 列号
            text = table.item(self.row, 'value')[col - 1]  # 单元格内容
            x = table.bbox(self.row, column=col - 1)[0]  # 单元格x坐标
            y = table.bbox(self.row, column=col - 1)[1]  # 单元格y坐标
            width = table.bbox(self.row, column=col - 1)[2]  # 单元格宽度
            height = table.bbox(self.row, column=col - 1)[3]  # 单元格高度

            self.entry.focus_set()  # 输入条获取焦点
            self.entry.delete(0, END)  # 清除输入条中的内容
            self.entry.place(x=x, y=y, width=width, height=height)  # 设置输入条位置及长宽
            self.entry.insert(0, text)  # 输入条插入内容

    # 鼠标滚轮触发
    def on_MouseWheel(self, event):
        if self.entry.winfo_viewable() == 1:  # 如果输入条可见
            text = self.entry.get()  # 获取输入条内容
            self.table.set(self.row, self.column, text)  # 表格数据设置为输入条内容
            self.entry.place_forget()  # 隐藏输入条

    # 回车键触发
    def on_Return(self, event):
        if self.entry.winfo_viewable() == 1:  # 如果输入条可见
            self.entry.place_forget()  # 隐藏输入条
            text = self.entry.get()  # 获取输入条内容
            self.table.set(self.row, self.column, text)  # 表格数据设置为输入条内容

    # X轴滚动条拖动触发
    def on_X_ScrollCommand(self, *xx):
        if self.entry.winfo_viewable() == 1:  # 如果输入条可见
            text = self.entry.get()  # 获取输入条内容
            self.table.set(self.row, self.column, text)  # 表格数据设置为输入条内容
            self.entry.place_forget()  # 隐藏输入条
        self.table.xview(*xx)  # 表格横向滚动

    # Y轴滚动条拖动触发
    def on_Y_ScrollCommand(self, *xx):
        if self.entry.winfo_viewable() == 1:  # 如果输入条可见
            text = self.entry.get()  # 获取输入条内容
            self.table.set(self.row, self.column, text)  # 表格数据设置为输入条内容
            self.entry.place_forget()  # 隐藏输入条
        self.table.yview(*xx)  # 表格纵向滚动


if __name__ == '__main__':
    root = tk.Tk()
    root.geometry('800x300')
    root.title("TreeView演示")
    MyTable(root)
    root.mainloop()